package text.ui;

import java.awt.BorderLayout;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;

public class HelpViewer extends Viewer {

    private JEditorPane html = null;
    
    /**
     * main method allows us to run as a standalone demo.
     */
    public static void main(String[] args) {
		HelpViewer helpViewer = new HelpViewer();
		helpViewer.init();
    }
    
    /**
     * HelpViewer Constructor
     */
    public HelpViewer() {
        // Set the title for this demo, and an icon used to represent this
        // demo inside the GUI app.
        super(null, "HelpViewer", "help.GIF");
	
        try {
		    URL url = null;
		    // System.getProperty("user.dir") +
		    // System.getProperty("file.separator");
		    String path = null;
		    
		    try {
				path = "/resources/users_manual/index.html";
				url = getClass().getResource(path);
		    } catch (Exception e) {
				System.err.println("Failed to open " + path);
				url = null;
	        }
		    
            if(url != null) {
                html = new JEditorPane(url);
                html.setDragEnabled(true);
                html.setEditable(false);
                html.addHyperlinkListener(createHyperLinkListener());

				JScrollPane scroller = new JScrollPane();
				JViewport vp = scroller.getViewport();
				vp.add(html);
                getViewerPanel().add(scroller, BorderLayout.CENTER);
            }
        } catch (MalformedURLException e) {
            System.out.println("Malformed URL: " + e);
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
    }

    private HyperlinkListener createHyperLinkListener() {
		return new HyperlinkListener() {
		    public void hyperlinkUpdate(HyperlinkEvent e) {
				if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
				    if (e instanceof HTMLFrameHyperlinkEvent) {
						((HTMLDocument)html.getDocument()).processHTMLFrameHyperlinkEvent(
						    (HTMLFrameHyperlinkEvent)e);
				    } else {
						try {
						    html.setPage(e.getURL());
						} catch (IOException ioe) {
						    System.out.println("IOE: " + ioe);
						}
				    }
				}
		    }
		};
    }
}